package com.midi.repnet.main;


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.*;

import com.midi.repnet.models.ChequeResults;
import com.midi.repnet.models.CreditElement;
import com.midi.repnet.ui.ViewGenerator;

import java.util.*;
import java.sql.*;
import java.awt.print.*;

public class Printer extends JFrame implements ActionListener, Printable,Pageable
{
	
	private JTable table, titleTable;
	private JToolBar toolbar;
	private JLabel lbl1;
	private JButton btnprint,btnremove;
	private JPanel pnl1, chkpnl1, chkpnl2;
	private JTextArea txtarea;
	private JTableHeader header;
	private int printWidth;
	private int headerHeight;
	private int rowHeight;
	private Object[][] data;
	private int tableWidth;
	private DefaultTableModel model;
	private String region;
	private int printType;
       
       private PageFormat defaultPageFormat = new PageFormat();

       public Printer(ArrayList<?> dataList, String[] columnNames, int type, String region_name)
		throws Exception {
              setSize(630,575);
              setTitle("Reports");
              btnprint = new JButton("Print");
              btnprint.addActionListener(this); 
              btnremove = new JButton("Remove Entry");
              btnremove.addActionListener(this); 
              toolbar = new JToolBar();
              switch (type) {
              case ViewGenerator.REPORT_TYPE_CREDIT_OVERDUE:

                      break;
              case ViewGenerator.REPORT_TYPE_CHEQUE_RESULTS:
            	  
                  data = new Object[dataList.size()][columnNames.length];
                  ArrayList<ChequeResults> chequeList = (ArrayList<ChequeResults>)dataList;
                    for ( int i = 0; i < chequeList.size(); i++ ) {
                  	  ChequeResults cr = chequeList.get(i);
                  	  Object[] line = { cr.getDate(),cr.getBill_no(),cr.getShop(),cr.getCheque_no(),cr.getBank(),Float.toString(cr.getAmount()),cr.getStatus() };
                  	  data[i] = line;
      			
                    }      			
                    System.out.println("-----------COL::" + columnNames.length);


                      break;
              case ViewGenerator.REPORT_TYPE_CREDIT_COLLECTION:
            	  this.region=region_name;
            	  this.printType=type;
            	  data = new Object[dataList.size()][columnNames.length];
            	  ArrayList<CreditElement> creditElements = (ArrayList<CreditElement>)dataList;
                  for ( int i = 0; i < creditElements.size(); i++ ) {
                	  CreditElement l = creditElements.get(i);
                  	  Object[] line = { l.getDate(), l.getBill_no(),
                              l.getShop(), l.getRegion(), l.getAgency(),
                              l.getAmount(),
                              l.getRemainder(),null,null,null  };
                  	  data[i] = line;
      			
                    }      	  
            	  
            	  
                      break;
              case ViewGenerator.REPORT_TYPE_CREDIT_PAID:

                      break;
              }


              
              model = new DefaultTableModel(data, columnNames) {
      			public boolean isCellEditable(int row, int column) {
      				return false;// This causes all cells to be not editable
      			}
      		};

              
  			table = new JTable(model){  
  			  public boolean isCellEditable(int row, int column){  
  			    return false;  
  			  }  
  			};  
  			
  			
  			DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
  			rightRenderer.setHorizontalAlignment( JLabel.RIGHT );
  			table.getColumnModel().getColumn(5).setCellRenderer( rightRenderer );
  			table.getColumnModel().getColumn(6).setCellRenderer( rightRenderer );
  			
  			//table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
  			setWidth(table);
  			// table.setBorder(BorderFactory.createLineBorder(Color.black));
  			header = table.getTableHeader();
  			headerHeight = header.getPreferredSize().height;
  			rowHeight = table.getRowHeight();  			
  			System.out.println("-----------H::" + table.getHeight());
  			System.out.println("-----------W::" + table.getWidth());   

              
              Font fnt = new Font("serif",Font.BOLD,16);
              
              lbl1 = new JLabel("DON BOSCO SCHOOL LIBRARY");
              lbl1.setBorder(BorderFactory.createEmptyBorder(10,0,10,0));
              lbl1.setHorizontalAlignment(JLabel.CENTER);
              lbl1.setFont(fnt);
              pnl1 = new JPanel();
              chkpnl1 = new JPanel();
              chkpnl2 = new JPanel();               
              
              JScrollPane scrollpane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//txtarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
        
              
              
              toolbar.add(btnprint);
              toolbar.add(btnremove);
              getContentPane().add(toolbar,BorderLayout.NORTH);
              getContentPane().add(scrollpane);
              
       }
       
       
//       public Printer(JTable table)
//		throws Exception {
//              setSize(630,575);
//              setTitle("Reports");
//              btnprint = new JButton("Print");
//              btnprint.addActionListener(this);              
//              toolbar = new JToolBar();
////              switch (type) {
////              case ViewGenerator.REPORT_TYPE_CREDIT_OVERDUE:
////
////                      break;
////              case ViewGenerator.REPORT_TYPE_CHEQUE_RESULTS:
////            	  
////                  data = new Object[dataList.size()][columnNames.length];
////                  ArrayList<ChequeResults> chequeList = (ArrayList<ChequeResults>)dataList;
////                    for ( int i = 0; i < chequeList.size(); i++ ) {
////                  	  ChequeResults cr = chequeList.get(i);
////                  	  Object[] line = { cr.getDate(),cr.getBill_no(),cr.getShop(),cr.getCheque_no(),cr.getBank(),Float.toString(cr.getAmount()),cr.getStatus() };
////                  	  data[i] = line;
////      			
////                    }      			
////                    System.out.println("-----------COL::" + columnNames.length);
////
////
////                      break;
////              case ViewGenerator.REPORT_TYPE_CREDIT_COLLECTION:
////
////            	  data = new Object[dataList.size()][columnNames.length];
////            	  ArrayList<CreditElement> creditElements = (ArrayList<CreditElement>)dataList;
////                  for ( int i = 0; i < creditElements.size(); i++ ) {
////                	  CreditElement l = creditElements.get(i);
////                  	  Object[] line = { l.getDate(), l.getBill_no(),
////                              l.getShop(), l.getRegion(), l.getAgency(),
////                              Float.toString(l.getAmount()),
////                              Float.toString(l.getRemainder())  };
////                  	  data[i] = line;
////      			
////                    }      	  
////            	  
////            	  
////                      break;
////              case ViewGenerator.REPORT_TYPE_CREDIT_PAID:
////
////                      break;
////              }
////
////
////  			table = new JTable(data, columnNames){  
////  			  public boolean isCellEditable(int row, int column){  
////  			    return false;  
////  			  }  
////  			};  
//  			//table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
//  			setWidth(table);
//  			// table.setBorder(BorderFactory.createLineBorder(Color.black));
//  			header = table.getTableHeader();
//  			headerHeight = header.getPreferredSize().height;
//  			rowHeight = table.getRowHeight();  			
//  			System.out.println("-----------H::" + table.getHeight());
//  			System.out.println("-----------W::" + table.getWidth());   
//
//              
//              Font fnt = new Font("serif",Font.BOLD,16);
//              
//              lbl1 = new JLabel("DON BOSCO SCHOOL LIBRARY");
//              lbl1.setBorder(BorderFactory.createEmptyBorder(10,0,10,0));
//              lbl1.setHorizontalAlignment(JLabel.CENTER);
//              lbl1.setFont(fnt);
//              pnl1 = new JPanel();
//              chkpnl1 = new JPanel();
//              chkpnl2 = new JPanel();               
//              
//              JScrollPane scrollpane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//txtarea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
//        
//              
//              
//              toolbar.add(btnprint);              
//              getContentPane().add(toolbar,BorderLayout.NORTH);
//              getContentPane().add(scrollpane);
//              
//       }
       
       
       
       
       
       
       private int getNumberOfRowsByPage() {
              double tableAvailableSpaceByPage = defaultPageFormat.getImageableHeight()-headerHeight;
              return((int)Math.floor(tableAvailableSpaceByPage/rowHeight));
       }

       private int getTableVerticalShiftForIndex(int index) {
              int shiftY = (getNumberOfRowsByPage()*rowHeight*index);
              return(shiftY);
       }

       public int getNumberOfPages() {
              int nbPages = (int)Math.ceil(table.getRowCount()/(double)getNumberOfRowsByPage());
              return(nbPages);
       }

       public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
              if (pageIndex<1 && pageIndex>getNumberOfPages()) {
                     throw new IndexOutOfBoundsException("Page "+pageIndex+" doesn't exist!");
              }
              else {
                     return(defaultPageFormat);
              }
       }

       public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
              if (pageIndex<1 && pageIndex>getNumberOfPages()) {
                     throw new IndexOutOfBoundsException("Page "+pageIndex+" doesn't exist!");
              }
              else {
                     return(this);
              }
       }

       public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
              printWidth = table.getWidth();
              System.out.println("THE PRINT WIDTH::"+printWidth);
              if (pageIndex<1 && pageIndex>getNumberOfPages()) {
                     return Printable.NO_SUCH_PAGE;
              }      
              Graphics2D g = (Graphics2D)graphics;
              double scaleX = pageFormat.getImageableWidth()/printWidth;
              boolean needScale = scaleX < 1;
              g.translate(pageFormat.getImageableX(),pageFormat.getImageableY());
              if (needScale) {
                     g.scale(scaleX,1);
              }

              JLabel label = new JLabel("Lathpandura Holdings");
              label.setFont(new Font("Sans Serif", Font.PLAIN, 20));
              label.setBounds(0, 0, printWidth, 30);
              g.translate(0,0);
              g.setClip(0,0,printWidth,30);
              label.printAll(g);
              
              if(printType==ViewGenerator.REPORT_TYPE_CREDIT_COLLECTION && !region.equals("Choose Region")){
                  JLabel llabel = new JLabel("Region: "+region);
                  llabel.setFont(new Font("Sans Serif", Font.PLAIN, 10));
                  llabel.setBounds(0, 0, printWidth, 30);
                  g.translate(0,30);
                  g.setClip(0,0,printWidth,30);
                  llabel.printAll(g);
              }              
              
              g.translate(0,50);
              g.setClip(0,0,printWidth,headerHeight);
              System.out.println("-------H---------"+headerHeight);
              
              header.printAll(g);
              g.translate(0,headerHeight);
              g.setClip(0,0,printWidth, getNumberOfRowsByPage()*rowHeight);
              g.translate(0,-getTableVerticalShiftForIndex(pageIndex));
              table.printAll(g);
              return Printable.PAGE_EXISTS;
       }


       public void actionPerformed(ActionEvent ae)
       {
              Object obj = ae.getSource();
              if(obj==btnprint)
              {
            	  
  				// add password to print button

  				int id = 2;
  				boolean check = PasswordChecker.checkResult(id);
  				// Uses boolean to determine if password is valid
  				if (check == true) {             	  
              	  
                    PrinterJob printerJob = PrinterJob.getPrinterJob();
                    printerJob.setJobName("Printing Report");
                    defaultPageFormat = printerJob.defaultPage();
                    defaultPageFormat = printerJob.pageDialog(defaultPageFormat);
                    printerJob.setPageable(this);
                    if (printerJob.printDialog()) 
                    {                    
                          try {
                                 printerJob.print();
                                 System.out.println("Coming here TO print");
                          }
                          catch (PrinterException e)
                          {
                                 System.out.println(e);
                          }      
                    }

  				} else {
  					JOptionPane.showMessageDialog(null,
  							"Enter Correct Password");

  				}



              }
              
              
              else if(obj==btnremove){
            	  int selectedRow=table.getSelectedRow();            	  
            	  model.removeRow(selectedRow);
            	  
              }
              
       }

       
   	/*
   	 * To set the column width of a JTable according to the
            * largest entry in the column
   	 */
   	void setWidth(JTable table) {
   		TableModel model = table.getModel();
   		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
   		
           // a margin in pixel that will be applied of both sides
   		int margin = 4;
   		int colCount = model.getColumnCount();
   		int rowCount = model.getRowCount();
   		DefaultTableColumnModel colModel  = (DefaultTableColumnModel) table.getColumnModel();

   		for (int i = 0; i < colCount; i++) {
   			TableColumn col = colModel.getColumn(i);

   			// Get width of column header
   			TableCellRenderer renderer = col.getHeaderRenderer();
               // if the column does not have a personalized renderer
   			if (renderer == null) {
   				renderer = table.getTableHeader().getDefaultRenderer();
   			}

   			Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);

   			int width = comp.getPreferredSize().width;

   			// Get maximum width of column data
   			for (int r = 0; r < rowCount; r++) {
   				renderer = table.getCellRenderer(r, i);
   				comp     = renderer.getTableCellRendererComponent(table, table.getValueAt(r, i), false, false,
   						r, i);
   				width = Math.max(width, comp.getPreferredSize().width);
   			}

   			// Add margin on both sides
   			width += 2 * margin;

   			// Set the preferred width
   			col.setPreferredWidth(width);
   		}
   	}
       
}